const bcrypt = require('bcryptjs');
const db = require('../../database')
const decrypt = require('./decrypt')
const getToken = require('./getToken')
const path = require('path')
const fs = require('fs')
const setDefaultAvatar = require('./setDefaultAvatar')
const writeLogs = require('./writeLogs')

module.exports = (req, res) => {
    const {username, password, mail} = req.body;
    const decrypted = decrypt(password);
    const hash = bcrypt.hashSync(decrypted, 10);
    const insert = 'insert into users (username, password, mail) values (?, ?, ?)';
    fs.mkdir(path.join(__dirname, '../../', 'pics', username), (err) => {
        if (err) console.log(err)
    });
    db.query(insert, [username, hash, mail], (err, data)=>{
        if (err) return res.cc(err)
        if (data.affectedRows === 0) return res.cc('数据库注册失败！')
        const ava = setDefaultAvatar(username);
        if (ava !== 0) return res.cc(ava)
        writeLogs('register', {
            username,
            mail,
        })
        res.cc(getToken(username), 0)
    })
}